package com.dgut.Controller;

import com.dgut.Service.AuthService;
import com.dgut.Service.impl.IUserDetailService;
import com.dgut.domain.Auth;
import com.dgut.utils.JwtAuthenticationResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class UserController {

    @Value("${jwt.header}")
    private String tokenHeader;


    @Autowired
    private IUserDetailService iUserDetailService;

    @Autowired
    private AuthService authService;

    @RequestMapping("/test")
    public String test() {
        Auth  response = authService.login("cmj","12345");
        System.out.println(response);
        return "test";
    }

    @ResponseBody
    @PostMapping(value = "/login")
    public ResponseEntity<?> testLogin(String username, String password){
        Auth auth = authService.login(username, password);
        return ResponseEntity.ok(new JwtAuthenticationResponse(auth.getToken()));
    }


//    @RequestMapping(value = "/logout",method = RequestMethod.GET)
//    public ResultJson testLogout(HttpServletRequest request){
//        String token = request.getHeader(tokenHeader);
//        if (token == null) {
//            System.out.println(ResultCode.UNAUTHORIZED);
//        }
//        authService.logout(token);
//        return ResultJson.ok();
//    }


    @RequestMapping("/testLogout")
    public ResponseEntity<?> testLogOut(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        if(token == null)
            System.out.println("token has not register");

        authService.logout(token);
        return ResponseEntity.ok("you are logout");
    }



    @PostMapping(value = "/testLogin")
    public String testLoginAfter(HttpServletRequest httpServletRequest,HttpServletResponse response) throws IOException {

        return "has login";
    }


    @GetMapping(value = "/testUser")
    public void testUser(String token){
        System.out.println(SecurityContextHolder.getContext().getAuthentication().getPrincipal());
        System.out.println(authService.getUserByToken(token).getiRole().getRole_name());
    }


    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @RequestMapping("/testRole")
    public String testRole(){
        return "admin role";
    }

}
